import * as vscode from 'vscode';

class ClaudeTerminalManager {
    private terminalCounter: number = 0;
    private terminalBusyState: Map<vscode.Terminal, boolean> = new Map();
    private context: vscode.ExtensionContext;

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
    }

    /**
     * 创建新标签页终端
     */
    createNewTabTerminal(commandName: string, command: string): vscode.Terminal {
        this.terminalCounter++;
        
        // 判断是否是Claude相关命令，选择对应图标
        const iconName = command.toLowerCase().startsWith('claude') ? 'comment-discussion' : 'terminal';
        
        const terminal = vscode.window.createTerminal({
            name: `${commandName} ${this.terminalCounter}`,
            iconPath: new vscode.ThemeIcon(iconName),
            location: { viewColumn: vscode.ViewColumn.Beside }, // 在新的视图列中打开
            isTransient: true // 设置为临时终端
        });
        
        // 显示终端
        terminal.show();
        this.terminalBusyState.set(terminal, false);
        
        // 执行命令
        terminal.sendText(command);
        
        return terminal;
    }

    /**
     * 打开Claude终端
     */
    openClaudeTerminal(): void {
        const commandName = 'Claude';
        const command = 'claude --dangerously-skip-permissions';
        
        try {
            this.createNewTabTerminal(commandName, command);
            vscode.window.showInformationMessage(`${commandName} ${this.terminalCounter} 已在新标签页中启动！`);
        } catch (error) {
            vscode.window.showErrorMessage(`启动Claude失败: ${error}`);
        }
    }
}

export function activate(context: vscode.ExtensionContext) {
    console.log('Claude Terminal Tab extension is now active!');

    // 创建终端管理器
    const terminalManager = new ClaudeTerminalManager(context);

    // 注册命令：在新标签页中打开Claude
    const openClaudeCommand = vscode.commands.registerCommand('claude.openNewTabTerminal', () => {
        terminalManager.openClaudeTerminal();
    });

    context.subscriptions.push(openClaudeCommand);
}

export function deactivate() {
    console.log('Claude Terminal Tab extension is deactivated');
}